extends Control

const DialogItem = preload("res://tool/page/dialog/paragraph/DialogItem.tscn")
const CombinationDialogItem = preload("res://tool/page/dialog/paragraph/CombinationDialogItem.tscn")
const RandomDialogItem = preload("res://tool/page/dialog/paragraph/RandomDialogItem.tscn")

onready var content_box = $box/table/ScrollContainer/VBoxContainer
onready var type_op = $box/HBoxContainer/type/typeOp


signal close
signal add_dialog(data)


var edit_data = null

func _ready():
	pass 



# 添加对话项
func _on_addItem_button_up():
	var ItemUi = DialogItem
	if type_op.get_selected_id() == 1:
		ItemUi = CombinationDialogItem
	if type_op.get_selected_id() == 2:
		ItemUi = RandomDialogItem
		
	
	content_box.add_child(ItemUi.instance())
	


func set_data(data):
	self.edit_data = data
	
	if data:
		$box/HBoxContainer/name/name.text = data["name"]
		$box/desc/remark.text = data["remark"]
		
		type_op.select(type_op.get_item_index(data["type"]))
		
		for child in content_box.get_children():
			child.queue_free()
		
		
		var ItemUi = DialogItem
		if type_op.get_selected_id() == 1:
			ItemUi = CombinationDialogItem
		if type_op.get_selected_id() == 2:
			ItemUi = RandomDialogItem
		
		for content_data in data.get("contents", []):
			var item_ui = ItemUi.instance()
			content_box.add_child(item_ui)
			item_ui.set_data(content_data)
		
		$box/modalTitle.text = "编辑对话：%s" % [data["name"]]
		$box/btns/ok.text = "保存"
	else:
		$box/modalTitle.text = "创建对话"
		$box/btns/ok.text = "添加"
		
		$box/HBoxContainer/name/name.text = ""
		$box/desc/remark.text = ""
		
		type_op.select(type_op.get_item_index(0))
		
		for child in content_box.get_children():
			child.queue_free()
		
	
func get_data():
	var data = {
		"name": $box/HBoxContainer/name/name.text,
		"remark": $box/desc/remark.text,
		"type": type_op.get_selected_id(),
	}
	
	var contents = []
	
	for item in content_box.get_children():
		contents.append(item.get_data())
	
	data["contents"] = contents
	
	return data
	


func _on_ok_button_up():
	var data = get_data()
	
	if edit_data:
		data["id"] = edit_data["id"]
		DataSource.update_data(DataSource.dialig, data)
	else:
		data["id"] = get_dialog_id()
		DataSource.add_data(DataSource.dialig, data)
	
	visible = false
	
	emit_signal("add_dialog", data)

	for item in content_box.get_children():
		item.queue_free()

func get_dialog_id():
	var dialigs = DataSource.get_data_list(DataSource.dialig)
	
	var max_id = 0
	for data in dialigs:
		var id = replace_id(data["id"])
		max_id = max(max_id, id)
	
	return str(max_id + 1)


func replace_id(id):
	return int(id.replace("_", ""))


func _on_cancel_button_up():
	
	visible = false
	emit_signal("close")
	
	for item in content_box.get_children():
		item.queue_free()

# 切换类型，清空所有对话项
func _on_typeOp_item_selected(index):
	for child in content_box.get_children():
		child.queue_free()
